import {getReserveList, putReserveApply, putReserveReject, putReserveExamine} from '../../../api/admin/reserve.js'
import {useEffect, useState} from "react";
import {
    Table,
    Button,
    Pagination,
    Form,
    Row,
    Col,
    Input,
    DatePicker,
    message,
    Badge,
    Popconfirm,
    Modal,
    Radio
} from 'antd';
import dayjs from 'dayjs';
import './reserve.less'
import {useNavigate} from "react-router-dom";

const Reserve = () => {
    const [form] = Form.useForm();
    const {RangePicker} = DatePicker;
    const [list, setList] = useState([])
    const [pageSize, setPageSize] = useState(10)
    const [pageNum, setPageNum] = useState(1)
    const [total, setTotal] = useState(0)


    let [createdStartTime, setCreatedStartTime] = useState('')
    let [createdEndTime, setCreatedEndTime] = useState('')

    const onShowSizeChange = (current, pageSize) => {
        setPageNum(1)
        setPageSize(pageSize)
        getList(1, pageSize)
    }
    const onChange = (pageNum, pageSize) => {
        setPageNum(pageNum)
        getList(pageNum, pageSize)
    };

    useEffect(() => {
        getList(1, 10)
    }, [])

    const getList = (pageNum, pageSize) => {
        console.log(createdStartTime, createdEndTime);
        const list = {
            username: form.getFieldValue('username'),
            meetingName: form.getFieldValue('meetingName'),
            meetingPosition: form.getFieldValue('meetingPosition'),
            bookingTimeRangeStart: form.getFieldValue('bookingTimeRange') ? form.getFieldValue('bookingTimeRange')[0] : '',
            bookingTimeRangeEnd: form.getFieldValue('bookingTimeRange') ? form.getFieldValue('bookingTimeRange')[1] : '',
            pageNum: pageNum,
            pageSize: pageSize
        }
        getReserveList(list)
            .then(res => {
                setList(res.data.bookings)
                setPageSize(res.data.pageSize)
                setPageNum(res.data.pageNum)
                setTotal(res.data.total)
            })
            .catch(err => {
                console.log(err, 'err');
            })
    }

    const putReserveApplyList = (id) => {
        putReserveApply(id)
            .then(res => {
                const {code} = res
                if (code === 200) {
                    message.success('审批通过');
                    getList()
                } else {
                    message.error('审批失败');
                }
            })
            .catch(err => {
                console.log(err, 'err');
            })
    }

    const putReserveRejectList = (id) => {
        putReserveReject(id)
            .then(res => {
                const {code} = res
                if (code === 200) {
                    message.success('驳回成功');
                    getList()
                } else {
                    message.error('审批失败');
                }
            })
            .catch(err => {
                console.log(err, 'err');
            })
    }

    const putReserveExamineList = (id, status) => {
        const list = {
            id: modalId,
            status: value === 0
        }
        putReserveExamine(list)
            .then(res => {
                console.log(res, 'res')
                const {code} = res
                if (code === 200) {
                    message.success(status ? '停用成功' : '启用成功');
                    setIsModalOpen(false);
                    setValue(0);
                    getList(1, pageSize)
                } else {
                    message.error(status ? '停用失败' : '启用失败');
                }
            })
            .catch(err => {
                console.log(err, 'err');
            })
    }

    const columns = [
        // {
        //     title: '序号', align: 'center', width: 60, render: (text, record, index) => {
        //         return <>{index + 1}</>
        //     },
        // },
        {
            title: '预约ID',
            dataIndex: 'id',
            key: 'id',
            width: 100,
            render: (text, record) => <span>{text}</span>,
        },
        {
            title: '预约用户', width: 160,
            render: (text, record) => <span>{record.user.username}</span>,
        },
        {
            title: '预约昵称', width: 160,
            render: (text, record) => <span>{record.user.nickName}</span>,
        },
        {
            title: '预约会议室', width: 200,
            render: (text, record) => <span>{record.room.name}</span>,
        },
        {
            title: '会议室位置', width: 200,
            render: (text, record) => <span>{record.room.location}</span>,
        },
        {
            title: '预约时间', width: 150, render: (text, record) => (
                <div>
                    <div>
                        {dayjs(record.startTime).format("YYYY-MM-DD HH:mm:ss")}
                    </div>
                    <div>
                        {dayjs(record.endTime).format("YYYY-MM-DD HH:mm:ss")}
                    </div>
                </div>
            )
        },
        {
            title: '状态', dataIndex: 'status', key: 'status', width: 80, render: (text) => (<span>
                {text === '申请中' && <Badge status="processing" text={text}/>}
                {text === '审批通过' && <Badge status="success" text={text}/>}
                {text === '审批驳回' && <Badge status="error" text={text}/>}
                {text === '已解除' && <Badge status="default" text={text}/>}
               </span>)
        },
        {
            title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 150, render: (text) => (<span>
          {dayjs(text).format("YYYY-MM-DD HH:mm:ss")}
        </span>)
        },
        {
            title: '操作', fixed: 'right', width: 150, render: (text, record) => (<span>
                {record.status === '申请中' &&
                    <Button type="link" onClick={() => {
                        setIsModalOpen(true)
                        setModalId(record.id)
                    }}>审核</Button>
                }
                {record.status === '申请中' &&
                    <Popconfirm
                        title="是否审批通过?"
                        onConfirm={() => putReserveApplyList(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="link">通过</Button>
                    </Popconfirm>}
                {record.status === '申请中' &&
                    <Popconfirm
                        title="是否驳回?"
                        onConfirm={() => putReserveRejectList(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="link">驳回</Button>
                    </Popconfirm>}
        </span>)
        },];


    const formItemLayout = {
        labelCol: {
            sm: {span: 6},
        }, wrapperCol: {
            sm: {span: 18},
        },
    }

    const inquire = () => {
        getList(1, pageSize)
    }
    const reset = () => {
        form.resetFields();
        getList(1, 10)
    }

    const onTimeChange = (date, dateString) => {
        setCreatedStartTime(dateString[0])
        setCreatedEndTime(dateString[1])
    }

    const navigate = useNavigate();

    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleOk = () => {
        putReserveExamineList()
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        setValue(0);
    };
    const [value, setValue] = useState(0);
    const [modalId, setModalId] = useState('')
    const onExeamineChange = (e) => {
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    };
    const {TextArea} = Input;
    return (<>
        <div className='filtrate'>
            <Form {...formItemLayout} form={form}>
                <Row gutter={36}>
                    <Col span={8}>
                        <Form.Item
                            name="username"
                            label="预定人"
                        >
                            <Input placeholder="请输入预定人"/>
                        </Form.Item>
                    </Col>

                    <Col span={8}>
                        <Form.Item
                            name="meetingName"
                            label="会议室名称"
                        >
                            <Input placeholder="请输入会议室名称"/>
                        </Form.Item>
                    </Col>

                    <Col span={8}>
                        <Form.Item
                            name="meetingPosition"
                            label="会议室位置"
                        >
                            <Input placeholder="请输入会议室位置"/>
                        </Form.Item>
                    </Col>


                    <Col span={8}>
                        <Form.Item
                            name="bookingTimeRange"
                            label="预定时间"
                        >
                            <RangePicker onChange={onTimeChange} style={{width: '100%'}} format='YYYY-MM-DD'
                                         placeholder="预定日期"/>
                        </Form.Item>
                    </Col>

                    <Col span={16}>
                        <div className='operation'>
                            <Button style={{marginRight: '10px'}} onClick={reset}>重置</Button>
                            <Button type="primary" onClick={inquire}>查询</Button>
                        </div>
                    </Col>
                </Row>
            </Form>
        </div>
        <div>
            <div className='table'>
                <Table rowKey='id' scroll={{x: 2000}} columns={columns} dataSource={list}
                       pagination={false}/>
            </div>

            <div className='pagination'>
                <Pagination
                    showSizeChanger
                    onShowSizeChange={onShowSizeChange}
                    onChange={onChange}
                    showTotal={(total) => `共${total}条记录 第${pageNum}/${Math.ceil(total / pageSize)}页`}
                    total={total}
                    current={pageNum}
                    pageSize={pageSize}
                />
            </div>
        </div>
        <div>
            <Modal title="审批" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Radio.Group onChange={onExeamineChange} value={value}>
                    <Radio value={0}>通过</Radio>
                    <Radio value={1}>驳回</Radio>
                </Radio.Group>

                {value === 1 && <TextArea
                    showCount
                    maxLength={100}
                    placeholder="请输入驳回原因"
                    style={{
                        height: 80,
                        margin: '20px 0',
                        resize: 'none',
                    }}
                />}
            </Modal>
        </div>
    </>)
}

export default Reserve